<template>
  <div class="compact-container">
    <!-- Compact search row -->
    <div class="search-row">
      <span class="search-label">客户名称（编码）：</span>
      <el-input v-model="customerName" size="small" class="search-input" />
      <span class="search-label">订单编号：</span>
      <el-input v-model="orderCode" size="small" class="search-input" />
      <span class="search-label">订单状态：</span>
      <el-select v-model="orderStatus" size="small" class="search-input">
        <el-option label="待出库" value="0" />
        <el-option label="部分出库" value="1" />
        <el-option label="全部出库" value="2" />
        <el-option label="部分退货" value="3" />
        <el-option label="全部退货" value="4" />
      </el-select>
      <span class="search-label">审核状态：</span>
      <el-select v-model="auditStatus1" size="small" class="search-input">
        <el-option label="待审核" value="0" />
        <el-option label="已审核" value="1" />
        <el-option label="已驳回" value="2" />
      </el-select>
      <el-button type="primary" size="small" @click="query">查询</el-button>
      <el-button size="small" @click="reset">重置</el-button>
      <div class="flex-grow"></div>
      <el-button type="primary" size="small" @click="exportToExcel">导出</el-button>
      <el-button type="primary" size="small" @click="addEdit">添加</el-button>
    </div>

    <el-divider style="margin: 6px 0" />

    <!-- Compact table area -->
    <div class="table-wrapper">
      <el-table :data="tableData" border style="width: 100%" :cell-style="{ textAlign: 'center', padding: '4px 0' }"
        :header-cell-style="{
          textAlign: 'center',
          background: '#f5f7fa',
          fontWeight: 'bold',
          position: 'sticky',
          top: 0,
          padding: '4px 0',
          height: '36px'
        }" :span-method="objectSpanMethod" ref="customerTable">
        <el-table-column fixed width="180px" prop="sale_order_code" label="订单编号">
          <template #default="scope">
            <el-link type="primary" @click="infoPage(scope.row.sale_order_code)">
              {{ scope.row.sale_order_code }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="sale_order_status" label="订单状态" width="180px" />
        <el-table-column prop="sale_order_audit_status" label="审核状态" width="180px">
          <template #default="scope">
            {{ scope.row.sale_order_audit_status == '0' ? "待审核" :
              scope.row.sale_order_audit_status == '1' ? "已审核" : "已驳回" }}
          </template>
        </el-table-column>
        <el-table-column prop="customer_name" label="客户名称" width="180px" />
        <el-table-column prop="sale_order_name" label="订单名称" width="180px" />
        <el-table-column prop="pro_name" label="产品名称" width="150px" />
        <el-table-column prop="pro_code" label="产品编号" width="180px" />
        <el-table-column prop="pro_brand" label="品牌" width="150px" />
        <el-table-column prop="pro_model" label="规格型号" width="180px" />
        <el-table-column prop="measure_id" label="单位">
          <template #default="scope">
            {{ measureValue(scope.row.measure_id) }}
          </template>
        </el-table-column>
        <el-table-column prop="pro_sale_qty" label="销售数量" width="100px" />
        <!-- <el-table-column prop="pro_outbound_qty" label="出库数量" width="100px" />
        <el-table-column prop="pro_return_qty" label="退货数量" width="100px" /> -->
        <el-table-column prop="sale_order_total_qty" label="销售总数量" width="150px" />
        <el-table-column prop="sale_order_total_price" label="销售总金额" width="150px" />
        <el-table-column prop="sale_order_sign_time" label="订单签订日期" width="190px" />
        <el-table-column prop="sale_order_deliver_time" label="订单交付日期" width="190px" />
        <el-table-column fixed="right" label="操作" width="240px" prop="action">
          <template #default="scope">
            <div class="action-group">
              <el-button size="small" @click="handleEdit(scope.row)"
                :disabled="scope.row.sale_order_audit_status === '1' || scope.row.sale_order_audit_status === '2'">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)"
                :disabled="scope.row.sale_order_audit_status === '1' || scope.row.sale_order_audit_status === '2'">删除</el-button>
              <el-button size="small" type="success" @click="handleAudit(scope.row)"
                :disabled="scope.row.sale_order_audit_status === '1' || scope.row.sale_order_audit_status === '2'">审核</el-button>
              <el-button size="small" type="warning" @click="handleRevoke(scope.row)"
                :disabled="scope.row.pro_outbound_qty != 0 || scope.row.pro_return_qty != 0 || scope.row.sale_order_audit_status !== '1'">撤销</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- Centered pagination -->
      <div class="pagination-center">
        <el-pagination small v-model:current-page="currentPage" v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]" :background="true" layout="total, sizes, prev, pager, next, jumper"
          :total="pageCount" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- Audit Dialog -->
    <el-dialog v-model="centerDialogVisible" width="385" align-center header-align="left">
      <template #header>
        <div style="text-align: left; font-size: 16px; font-weight: bold;">
          审核
        </div>
      </template>
      <hr>
      <div style="text-align: left;padding: 10px 0px;">
        <p>审核结果</p>
        <div class="my-2 ml-4">
          <el-radio-group v-model="auditStatus">
            <el-radio value="1">通过</el-radio>
            <el-radio value="2">驳回</el-radio>
          </el-radio-group>
        </div>
        <div>
          <p>审核意见</p>
          <el-input v-model="auditOpinion" style="width: 350px;height: 90px;" :autosize="{ minRows: 4, maxRows: 4 }"
            type="textarea" placeholder="请输入" />
        </div>
      </div>
      <hr>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="updateAudit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, markRaw, toRaw } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { WarnTriangleFilled } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { useStore } from 'vuex'

export default {
  setup() {
    const tableData = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const pageCount = ref(0)
    const measureOptios = ref([])
    const customerName = ref("")
    const orderCode = ref("")
    const store = useStore()
    const router = useRouter()
    const centerDialogVisible = ref(false)
    const auditStatus = ref('1')
    const auditOpinion = ref('')
    const sale_order_id = ref(0)
    const customerTable = ref(null)
    const orderStatus = ref("")
    const auditStatus1 = ref("")

    onMounted(() => {
      getMeasure()
      fill()
      count()
    })

    function getMeasure() {
      axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
          dict_type: "db_measure"
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        measureOptios.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function measureValue(row) {
      if (!row) return "无"
      const parentDept = measureOptios.value.find((sex) => sex.dict_value == row)
      return parentDept ? parentDept.dict_label : "无"
    }

    function fill() {
      axios.get("http://localhost:5181/api/Sinv_Sale_Order/GetSinv_Sale_Infos", {
        params: {
          currendPage: currentPage.value,
          pageSize: pageSize.value,
          customerName: customerName.value,
          orderCode: orderCode.value,
          orderStatus: orderStatus.value == "" ? -1 : orderStatus.value,
          auditStatus: auditStatus1.value == "" ? '3' : auditStatus1.value
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        tableData.value = transformOthwrData(result.data)
      }).catch((err) => {
        console.error(err)
      })
    }

    function count() {
      axios.get("http://localhost:5181/api/Sinv_Sale_Order/Sinv_Sale_OrderCOunt", {
        params: {
          customerName: customerName.value,
          orderCode: orderCode.value,
          orderStatus: orderStatus.value == "" ? -1 : orderStatus.value,
          auditStatus: auditStatus1.value == "" ? '3' : auditStatus1.value
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        pageCount.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    const transformOthwrData = (responseData) => {
      const result = []

      responseData.forEach((mainItem) => {
        mainItem.details.forEach((detail) => {
          let auditStatusText = ''
          switch (mainItem.sale_order_status) {
            case 0: auditStatusText = '待出库'; break
            case 1: auditStatusText = '部分出库'; break
            case 2: auditStatusText = '全部出库'; break
            case 3: auditStatusText = '部分退货'; break
            case 4: auditStatusText = '全部退货'; break
            default: auditStatusText = '未知出库状态'
          }

          result.push({
            sale_order_status: auditStatusText,
            sale_order_audit_status: mainItem.sale_order_audit_status,
            sale_order_id: mainItem.sale_order_id,
            sale_order_code: mainItem.sale_order_code,
            customer_name: mainItem.customer_name,
            sale_order_name: mainItem.sale_order_name,
            pro_name: detail.pro_name,
            pro_code: detail.pro_code,
            pro_brand: detail.pro_brand,
            pro_model: detail.pro_model,
            measure_id: detail.measure_id,
            pro_sale_qty: detail.pro_sale_qty,
            sale_order_total_qty: mainItem.sale_order_total_qty,
            sale_order_total_price: mainItem.sale_order_total_price,
            sale_order_sign_time: mainItem.sale_order_sign_time.replace('T', ' '),
            sale_order_deliver_time: mainItem.sale_order_deliver_time.replace('T', ' '),
            pro_planned_return_qty: detail.pro_planned_return_qty,
            pro_planned_outbound_qty: detail.pro_planned_outbound_qty,
            pro_return_qty: detail.pro_return_qty,
            pro_outbound_qty: detail.pro_outbound_qty
          })
        })
      })

      return result
    }

    const objectSpanMethod = ({ row, column, rowIndex }) => {
      const fieldsToMerge = [
        'sale_order_code',
        'sale_order_status',
        'customer_name',
        'sale_order_name',
        'sale_order_total_qty',
        'sale_order_total_price',
        'sale_order_sign_time',
        'sale_order_deliver_time',
        'action',
        "sale_order_audit_status"
      ]

      if (!fieldsToMerge.includes(column.property)) {
        return { rowspan: 1, colspan: 1 }
      }

      const currentGroup = row.sale_order_code

      if (rowIndex === 0 || tableData.value[rowIndex - 1].sale_order_code !== currentGroup) {
        let spanCount = 1

        while (
          rowIndex + spanCount < tableData.value.length &&
          tableData.value[rowIndex + spanCount].sale_order_code === currentGroup
        ) {
          spanCount++
        }

        if (column.property === 'action') {
          return { rowspan: spanCount, colspan: 1 }
        }

        let sameValueCount = 1
        while (
          rowIndex + sameValueCount < tableData.value.length &&
          tableData.value[rowIndex + sameValueCount].sale_order_code === currentGroup &&
          tableData.value[rowIndex + sameValueCount][column.property] === row[column.property]
        ) {
          sameValueCount++
        }

        return sameValueCount > 1
          ? { rowspan: sameValueCount, colspan: 1 }
          : { rowspan: 1, colspan: 1 }
      }
      else if (
        tableData.value[rowIndex - 1].sale_order_code === currentGroup &&
        tableData.value[rowIndex - 1][column.property] === row[column.property]
      ) {
        return { rowspan: 0, colspan: 0 }
      }
      else {
        let sameValueCount = 1

        while (
          rowIndex + sameValueCount < tableData.value.length &&
          tableData.value[rowIndex + sameValueCount].sale_order_code === currentGroup &&
          tableData.value[rowIndex + sameValueCount][column.property] === row[column.property]
        ) {
          sameValueCount++
        }

        return sameValueCount > 1
          ? { rowspan: sameValueCount, colspan: 1 }
          : { rowspan: 1, colspan: 1 }
      }
    }

    function handleSizeChange(val) {
      pageSize.value = val
      fill()
    }

    function handleCurrentChange(val) {
      currentPage.value = val
      fill()
    }

    function query() {
      fill()
      count()
    }

    function reset() {
      customerName.value = ""
      orderCode.value = ""
      orderStatus.value = ""
      auditStatus1.value = ""
      query()
    }

    function addEdit() {
      router.push('/main/Sinv/SalesOrderAdd')
    }

    function handleEdit(row) {
      if (row.sale_order_audit_status != '0') {
        ElMessage.warning('已审核过的订单不能再次编辑！')
        return
      }
      store.commit("SalesOrderCode", row.sale_order_code)
      router.push("/main/Sinv/SalesOrderUpdate")
    }

    function handleDelete(row) {

      if (row.sale_order_audit_status != '0') {
        ElMessage.warning('已审核过的订单不能删除！')
        return
      }

      ElMessageBox.confirm(
        '此操作将删除'+row.sale_order_code+'销售订单，是否继续？',
        '警告',
        {
          type: 'warning',
          icon: markRaw(Delete),
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }
      )
        .then(() => {
          const loadingInstance = ElLoading.service({
            lock: true,
            text: '正在删除中...',
            background: 'rgba(0, 0, 0, 0.7)',
          });
          axios.put("http://localhost:5181/api/Sinv_Sale_Order/Sinv_Sale_OrderDel", {
            sale_order_id: row.sale_order_id,
            del_flag: '1'
          }, {
            headers: {
              authorization: `Bearer ${localStorage.getItem('token')}`
            }
          }).then((result) => {
            if (result.data > 0) {
              ElMessage.success('删除成功！')
              fill()
              count()
            }
          }).catch((err) => {
            console.error(err)
          }).finally(() => {
            loadingInstance.close();
          })
        })
        .catch(() => {
          ElMessage.info('已取消删除')
        })
    }

    function handleAudit(row) {
      if (row.sale_order_audit_status != '0') {
        ElMessage.warning('已审核过的订单不能再次审核！')
        return
      }
      centerDialogVisible.value = true
      sale_order_id.value = row.sale_order_id
    }

    function updateAudit() {
      const loadingInstance = ElLoading.service({
        lock: true,
        text: '正在审核中...',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      axios.put("http://localhost:5181/api/Sinv_Sale_Order/Sinv_Sale_OrderAuditUpdate", {
        sale_order_id: sale_order_id.value,
        sale_order_audit_by: localStorage.getItem('userLName'),
        sale_order_audit_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
        sale_order_audit_opinion: auditOpinion.value,
        sale_order_audit_status: auditStatus.value
      }, {
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        if (result.data > 0) {
          if (auditStatus.value == '1') {
            ElMessage.success('审核通过')
          } else if (auditStatus.value == '2') {
            ElMessage.warning('审核已被驳回！')
          }
          close()
          fill()
          count()
        }
      }).catch((err) => {
        console.error(err)
      }).finally(() => {
        loadingInstance.close();
      })
    }

    function close() {
      centerDialogVisible.value = false
      auditStatus.value = "1"
      auditOpinion.value = ""
    }

    function infoPage(row) {
      store.commit("SalesOrderCode", row)
      router.push("/main/Sinv/SalesOrdereInfo")
    }

    function getTableHeaders() {
      if (customerTable.value) {
        const filteredColumns = customerTable.value.columns.filter(column => {
          return column.label !== '操作'
        })
        const headers = filteredColumns.map(column => column.label)
        return headers
      }
      return []
    }

    const exportToExcel = async () => {
      const headers = getTableHeaders()
      const row = toRaw(tableData.value)
      const headerMap = {
        '订单编号': 'sale_order_code',
        '订单状态': "sale_order_status",
        '审核状态': "sale_order_audit_status",
        '客户名称': 'customer_name',
        '订单名称': 'sale_order_name',
        '产品名称': 'pro_name',
        '产品编号': 'pro_code',
        '品牌': 'pro_brand',
        '规格型号': 'pro_model',
        '单位': 'measure_id',
        '销售数量': 'pro_sale_qty',
        '销售总数量': 'sale_order_total_qty',
        '销售总金额': "sale_order_total_price",
        '订单签订日期': 'sale_order_sign_time',
        '订单交付日期': 'sale_order_deliver_time'
      }

      const orderFields = [
        'sale_order_code',
        'sale_order_status',
        'sale_order_audit_status',
        'customer_name',
        'sale_order_name',
        'sale_order_total_qty',
        'sale_order_total_price',
        'sale_order_sign_time',
        'sale_order_deliver_time'
      ]

      let previousOrderCode = null

      const rowDataArray = row.map((item) => {
        const rowData = headers.map(header => {
          const propName = headerMap[header]
          const currentOrderCode = item.sale_order_code
          if (orderFields.includes(propName) && currentOrderCode === previousOrderCode) {
            return ''
          } else if (propName == "measure_id") {
            return measureValue(item[propName])
          } else if (propName == 'sale_order_audit_status') {
            return item[propName] == '0' ? "待审核" :
              item[propName] == '1' ? "已审核" : "已驳回"
          }
          else {
            return item[propName]
          }
        })
        previousOrderCode = item.sale_order_code
        return rowData
      })

      const mergeColumns = [
        '订单编号',
        '订单状态',
        '审核状态',
        '客户名称',
        '订单名称',
        '销售总数量',
        '销售总金额',
        '订单签订日期',
        '订单交付日期'
      ]
      try {
        const response = await axios.post('http://localhost:5181/api/SystemHome/ExportExcel', {
          headers: headers,
          rows: rowDataArray,
          title: "销售订单信息",
          mergeColumns: mergeColumns
        }, {
          responseType: 'blob'
        })

        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', '销售订单信息.xlsx')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      } catch (error) {
        console.error('导出 Excel 失败:', error)
      }
    }

    //撤销按钮
    function handleRevoke(row) {
      ElMessageBox.confirm(
        '此操作将删除该销售订单，是否继续？',
        '警告',
        {
          type: 'warning',
          icon: markRaw(WarnTriangleFilled),
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }
      )
        .then(() => {
          const loadingInstance = ElLoading.service({
            lock: true,
            text: '正在撤销中...',
            background: 'rgba(0, 0, 0, 0.7)',
          });
          axios.put("http://localhost:5181/api/Sinv_Sale_Order/Sinv_Sale_OrderRevoke", {
            sale_order_id: row.sale_order_id,
            sale_order_audit_status: '0'
          }, {
            headers: {
              authorization: `Bearer ${localStorage.getItem('token')}`
            }
          }).then((result) => {
            if (result.data > 0) {
              ElMessage.success('撤销成功！')
              fill()
              count()
            }
          }).catch((err) => {
            console.error(err)
          }).finally(() => {
            loadingInstance.close();
          })
        })
        .catch(() => {
          ElMessage.info('已取消撤销')
        })
    }

    return {
      tableData, currentPage, pageSize, pageCount, measureOptios, customerName, orderCode,
      centerDialogVisible, auditStatus, auditOpinion, sale_order_id, customerTable,
      measureValue, fill, count, handleSizeChange, handleCurrentChange, objectSpanMethod,
      query, reset, addEdit, handleEdit, handleDelete, handleAudit, updateAudit, close,
      infoPage, exportToExcel, handleRevoke, orderStatus, auditStatus1
    }
  }
}
</script>

<style scoped>
.compact-container {
  padding: 10px;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 6px;
  margin-top: -40px;
}

.search-label {
  white-space: nowrap;
  font-size: 13px;
}

.search-input {
  width: 160px !important;
}

.flex-grow {
  flex-grow: 1;
}

.table-wrapper {
  margin-top: 6px;
}

.pagination-center {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.action-group {
  display: flex;
  justify-content: center;
  gap: 4px;
}

.dialog-header {
  font-size: 16px;
  font-weight: bold;
  text-align: left;
}

.dialog-content {
  padding: 10px 0;
  text-align: left;
}

.radio-group {
  margin: 10px 0 20px 0;
}

.opinion-input {
  width: 100%;
  margin-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table__row) {
  height: 36px !important;
}

:deep(.el-table th.el-table__cell) {
  height: 36px !important;
}

:deep(.el-button--small) {
  padding: 5px 8px;
  height: 24px;
}
</style>